package com.yksj.healthtalk.ui.friend;

import java.util.ArrayList;
import java.util.Collection;

import org.handmark.pulltorefresh.library.PullToRefreshListView;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.FriendAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.adapter.FriendSearchAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.setting.PersonalInformationActivity;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.FriendUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 搜索朋友结果列表
 * 
 * @author Administrator
 * 
 */
public class FriendSearchListActivity extends BaseFragmentActivity implements
		OnClickListener, OnItemClickListener,onClickFriendHeadListener {

	private Intent intent;
	private boolean isContact = false;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView mListView;
	private FriendSearchAdapter adapter;
	private ArrayList<CustomerInfoEntity> entities;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private AppData mAppData;
	private Handler handler = new Handler();
	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
				
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getApplicationContext(), R.string.groupNewFail);
				} else if (result.equals("-1")) {
					ToastUtil.showShort(getApplicationContext(),R.string.against__blacklist_operations);
				} else {
					FriendHttpUtil.requestAttentionTofriendsResult(getApplicationContext(), cacheCustomerInfoEntity, mAppData);
					adapter.notifyDataSetChanged();
				}
				
			} 
		}
	};
	private LodingFragmentDialog mShowLodingDialog;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.friend_search_list);
		mAppData = HTalkApplication.getAppData();
		initWidget();
		initData();
	}

	private void initData() {
		mPullToRefreshListView.setRefreshing();
		entities = new ArrayList<CustomerInfoEntity>();
		intent = getIntent();
		if (intent.hasExtra("isContact")) {
			isContact = true;
			titleTextV.setText("他们在用壹健康");
			adapter = new FriendSearchAdapter(this, entities);
			mListView.setAdapter(adapter);
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					final String parame = FriendUtil.getPhoneContacts(FriendSearchListActivity.this);
					handler.post(new Runnable() {
						
						@Override
						public void run() {
							if (!TextUtils.isEmpty(SmartFoxClient.getLoginUserId())&& !TextUtils.isEmpty(parame)) {
								HttpRestClient.doHttpFindContactInHealth(SmartFoxClient.getLoginUserId(), parame,new responseHandler());
							} 
						}
					});
				}
			}).start();
		}

	}

	@Override
	protected void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		registerReceiver(receiver, filter);
		super.onStart();
	}
	
	@Override
	public void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}
	
	
	private void initWidget() {
		initTitle();
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.hall);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.addFooterView(LayoutInflater.from(this).inflate(R.layout.list_line_layout, null));
		titleLeftBtn.setOnClickListener(this);
		mListView.setOnItemClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.invite:
			//短信邀请
			if (v.getTag() != null && TextUtils.isEmpty(entities.get((Integer) v.getTag()).getId())) {
				Uri uri = Uri.parse("smsto:"+ entities.get((Integer) v.getTag()).getPoneNumber());
				Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
				intent.putExtra("sms_body", "嗨,我在用壹健康,好多朋友都在里边,就差你了,赶紧去下载,等你啊.http://yijiankangv.mobi/SJ/download.html");
				startActivity(intent);
			}else if(v.getTag() != null){
				cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(FriendSearchListActivity.this, null, entities.get((Integer) v.getTag()));
			}
			break;
		default:
			break;
		}
	}

	class responseHandler extends ObjectHttpResponseHandler {

		public responseHandler() {
			super();
		}
		@SuppressWarnings("unchecked")
		@Override
		public void onSuccess(int statusCode, Object response) {
			entities.clear();
			entities.addAll((Collection<? extends CustomerInfoEntity>) response);
			adapter.notifyDataSetChanged();
			super.onSuccess(statusCode, response);
		}
		
		@Override
		public void onFinish() {
			super.onFinish();
			mPullToRefreshListView.onRefreshComplete();
		}
		
		@Override
		public Object onParseResponse(String content) {
			return FriendHttpUtil.jsonAnalysisFriendEntity(content,true);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (0 < position && position < entities.size() + 1) {
				position = position - 1;
				CustomerInfoEntity entity = entities.get(position);
				if (!TextUtils.isEmpty(entity.getId())) {
					if (SmartFoxClient.getLoginUserId().equals(entity.getId())) {
						Intent intent = new Intent();
						intent.setClass(getApplicationContext(), PersonalInformationActivity.class);
						startActivity(intent);
					}else if(entity.isDoctor()){
						Intent intent = new Intent(getApplicationContext(), DoctorMainActivity.class);
						intent.putExtra("id", entity.getId());
						startActivity(intent);
					}else {
						FriendHttpUtil.onItemClick(this, entity);
					}
				}
		}

	}


	@Override
	public void onClickFriendHead(CustomerInfoEntity entity, int positon) {
		if (!TextUtils.isEmpty(entity.getId())) {
			if (SmartFoxClient.getLoginUserId().equals(entity.getId())) {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), PersonalInformationActivity.class);
				startActivity(intent);
			} else if (entity.getRoldid() == 777 || entity.getRoldid() == 888) {
				Intent intent = new Intent(getApplicationContext(), DoctorMainActivity.class);
				intent.putExtra("id", entity.getId());
				startActivity(intent);
			} else {
				Intent intent = new Intent();
				intent.setClass(getApplicationContext(), FriendInformUI.class);
				intent.putExtra("id", entity.getId());
				startActivity(intent);
			}
		}
	}


}